import 'package:easy_rich_text/easy_rich_text.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_model/home/home_tabs_entity.dart';
import 'package:tiktokadult/hj_model/home/module_detail_model.dart';
import 'package:tiktokadult/hj_model/list_base_model.dart';
import 'package:tiktokadult/hj_model/mine/task_center_data.dart';
import 'package:tiktokadult/hj_model/video_model.dart';
import 'package:tiktokadult/hj_page/home_business/home_cell_style/video_simple_cell_widget.dart';
import 'package:tiktokadult/hj_page/main_page/provider/msg_provider.dart';
import 'package:tiktokadult/hj_page/mine_business/mine_vip/mine_charge_vip_page.dart';
import 'package:tiktokadult/hj_utils/api_service/common_service.dart';
import 'package:tiktokadult/hj_utils/api_service/mine_service.dart';
import 'package:tiktokadult/hj_utils/api_service/vid_service.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/routers/jump_router.dart';
import 'package:tiktokadult/tools_base/global_store/store.dart';
import 'package:tiktokadult/tools_base/loading/loading_center_widget.dart';
import 'package:tiktokadult/tools_base/widget/net_image_widget.dart';

import '../../../../hj_utils/date_time_util.dart';
import '../../../pre_sale/pre_sale_provider.dart';
import '../../mine_vip/mine_charge_coin_page.dart';
import '../../mine_vip/mine_vip_sub_page.dart';
import '../../widgets/exchangeVipPage.dart';
import '../more_free_video_page.dart';

class TaskVIPVideosView extends StatefulWidget {
  const TaskVIPVideosView({super.key});

  @override
  State<TaskVIPVideosView> createState() => _TaskVIPVideosViewState();
}

class _TaskVIPVideosViewState extends State<TaskVIPVideosView> {
  ModuleData? vipModule;
  final dataSource = <Future<ListBaseModel<VideoModel>>>[];
  final rawData = <WareDiscountAreaData>[];
  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      final res = await VidService.fetchFreeareaVideoSource();
      rawData.addAll(res ?? []);
      res?.forEach((element) {
        dataSource.add(VidService.fetchFreeareaVideoSourceList(element.id ?? '', size: 4, sortType: 0));
      });
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    if (dataSource.isEmpty) return SizedBox.shrink();
    return ListView.separated(
      separatorBuilder: (_, __) => 12.sizeBoxH,
      itemCount: dataSource.length,
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      padding: EdgeInsets.symmetric(horizontal: 18.w),
      itemBuilder: (BuildContext context, int index) {
        final future = dataSource[index];
        final data = rawData[index];
        return FreeAreaVideoGridView(
          future,
          model: data,
        );
      },
    );
  }
}

class FreeAreaVideoGridView extends StatelessWidget {
  final Future<ListBaseModel<VideoModel>?> dataEntry;
  final WareDiscountAreaData? model;
  const FreeAreaVideoGridView(
    this.dataEntry, {
    super.key,
    this.model,
  });

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<ListBaseModel<VideoModel>?>(
      future: dataEntry,
      initialData: null,
      builder: (BuildContext context, AsyncSnapshot<ListBaseModel<VideoModel>?> snapshot) {
        if (!snapshot.hasData)
          return SizedBox(
            height: 340,
            child: LoadingCenterWidget(),
          );
        if (snapshot.hasError || snapshot.data == null || (snapshot.data?.list?.isEmpty ?? true)) return SizedBox.shrink();

        return SizedBox(
          height: 342,
          child: Stack(
            children: [
              Image.asset(
                'area_discount_bg.webp'.mineImgPath,
                height: double.infinity,
                fit: BoxFit.fill,
              ),
              Positioned.fill(
                child: Padding(
                  padding: EdgeInsets.symmetric(vertical: 20, horizontal: 8),
                  child: Column(
                    children: [
                      Row(
                        children: [
                          Text(
                            model?.title ?? '',
                            style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500),
                          ),
                          Spacer(),
                          GestureDetector(
                            onTap: () => Get.to(MoreFreeVideoPage(model?.title ?? "", model?.id ?? "")),
                            child: Row(
                              children: [
                                Text(
                                  '更多',
                                  style: TextStyle(
                                    color: Color(0xff999999),
                                    fontSize: 12,
                                  ),
                                ),
                                Icon(
                                  Icons.arrow_forward_ios_rounded,
                                  size: 10,
                                  color: Color(0xff999999),
                                ),
                              ],
                            ),
                          )
                        ],
                      ),
                      12.sizeBoxH,
                      Expanded(
                        child: LayoutBuilder(
                          builder: (BuildContext context, BoxConstraints constraints) {
                            final width = (constraints.maxWidth - 7) / 2;
                            final height = (constraints.maxHeight - 12) / 2;
                            return Wrap(
                              spacing: 7,
                              runSpacing: 12,
                              children: snapshot.data!.list!
                                  .map(
                                    (e) => SizedBox(
                                      width: width,
                                      height: height,
                                      child: VideoSimpleCellWidget(
                                        textLines: 1,
                                        // isShowTime: false,
                                        videoModel: e,
                                      ),
                                    ),
                                  )
                                  .toList(),
                            );
                          },
                        ),
                      )
                    ],
                  ),
                ),
              )
            ],
          ),
        );
      },
    );
  }
}

/// vip引导
class TaskCenterVIPGuideView extends StatefulWidget {
  const TaskCenterVIPGuideView({super.key});

  @override
  State<TaskCenterVIPGuideView> createState() => _TaskCenterVIPGuideViewState();
}

class _TaskCenterVIPGuideViewState extends State<TaskCenterVIPGuideView> {
  late final privilegeIcons = ['privilege_gold.webp'.mineImgPath, 'privilege_ai.webp'.mineImgPath, 'privilege_game.webp'.mineImgPath];
  late final privilegeTitles = ['至尊金币', 'AI科技', '成人游戏'];
  late final privilegeSubTs = ['价值100元', '价值500元', '价值1000元'];
  @override
  Widget build(BuildContext context) {
    return Consumer<GlobalStore>(builder: (_, store, __) {
      final isVip = store.isVIP();
      if (isVip) return _buildVIPGuide();
      return Column(
        children: [
          _buildVIPGuide(),
          Transform.translate(
            offset: Offset(0, -14),
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 15),
              decoration: BoxDecoration(
                  image: DecorationImage(
                image: AssetImage(
                  'vip_privilege_bg.webp'.mineImgPath,
                ),
                fit: BoxFit.fill,
              )),
              child: Column(
                children: [
                  18.sizeBoxH,
                  Row(
                    children: [
                      Image.asset(
                        'add_equal.png'.mineImgPath,
                        width: 14,
                        height: 14,
                      ),
                      10.sizeBoxW,
                      EasyRichText(
                        '开通荣耀至尊卡会员预计年省1800元',
                        defaultStyle: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w500),
                        patternList: [
                          EasyRichTextPattern(
                            targetString: '荣耀至尊卡|1800元',
                            style: TextStyle(color: Color(0xffE3C891), fontSize: 14, fontWeight: FontWeight.w500),
                          ),
                        ],
                      )
                    ],
                  ),
                  14.sizeBoxH,
                  Container(
                      height: 155,
                      child: GridView.builder(
                        shrinkWrap: false,
                        physics: NeverScrollableScrollPhysics(),
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 3,
                          childAspectRatio: 111 / 149,
                          crossAxisSpacing: 12,
                        ),
                        itemCount: 3,
                        itemBuilder: (context, index) {
                          return Column(
                            children: [
                              Expanded(
                                  child: Container(
                                width: double.infinity,
                                decoration: BoxDecoration(
                                  image: DecorationImage(
                                    image: AssetImage('privilege_bg.webp'.mineImgPath),
                                    fit: BoxFit.fill,
                                  ),
                                ),
                                child: Column(
                                  children: [
                                    14.sizeBoxH,
                                    Image.asset(
                                      privilegeIcons[index],
                                      height: 41,
                                      width: 41,
                                    ),
                                    1.sizeBoxH,
                                    Text(
                                      privilegeTitles[index],
                                      style: TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
                                    ),
                                    3.sizeBoxH,
                                    Text(
                                      privilegeSubTs[index],
                                      style: TextStyle(
                                        color: Color(0xff9FA19F),
                                        fontSize: 10,
                                      ),
                                    ),
                                  ],
                                ),
                              )),
                              6.sizeBoxH,
                              InkWell(
                                onTap: () => Get.to(MineChargeVipPage()),
                                child: Container(
                                  decoration: BoxDecoration(
                                    color: Color(0xffFFD5A8),
                                    borderRadius: BorderRadius.circular(18),
                                  ),
                                  width: 50,
                                  height: 24,
                                  alignment: Alignment.center,
                                  child: Text(
                                    '待领取',
                                    style: TextStyle(color: Color(0xff692A1F), fontSize: 10, fontWeight: FontWeight.w500),
                                  ),
                                ),
                              ),
                            ],
                          );
                        },
                      )),
                ],
              ),
            ),
          ),
        ],
      );
    });
  }

  Widget _buildVIPGuide() {
    return Stack(
      alignment: Alignment.centerLeft,
      children: [
        Image.asset(
          globalStore.isVIP() ? 'welfare_vip_bg.webp'.mineImgPath : 'welfare_normal_bg.webp'.mineImgPath,
          width: double.infinity,
          fit: BoxFit.fitWidth,
        ),
        Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SizedBox(width: 22),
            Expanded(
              child: Consumer<MineMsgProvider>(
                builder: (context, provider, child) => Container(
                  margin: EdgeInsets.only(left: 2),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(
                            globalStore.isVIP()
                                ? '${globalStore.meInfo?.vipName == null || globalStore.meInfo?.vipName == '' ? '普通会员' : globalStore.meInfo?.vipName}'
                                : '新人限时特惠',
                            style: TextStyle(
                              color: globalStore.isVIP() ? Color(0xffFFE7CD) : Colors.white,
                              fontSize: 14,
                            ),
                          ),
                          if (!globalStore.isVIP())
                            Container(
                              padding: EdgeInsets.only(top: 2),
                              child: Text(
                                ' 领取双倍每日登录积分',
                                style: TextStyle(color: Color(0xffE3C891), fontSize: 10),
                              ),
                            ),
                        ],
                      ),
                      SizedBox(height: 5),
                      Text(
                        globalStore.isVIP()
                            ? '${globalStore.vipTime(hasVipName: false)}'
                            : ((provider.countdown?.leftTimeSinceEpoch ?? 0) > 0)
                                ? '新人限时特惠  ${provider.countdown?.hourDesc ?? '00'}:${provider.countdown?.minDesc ?? '00'}:${provider.countdown?.secondsDesc ?? '00'}'
                                : '活动已结束',
                        style: TextStyle(color: Color(0xffE7E7E7), fontWeight: FontWeight.w400, fontSize: 11),
                      )
                    ],
                  ),
                ),
              ),
            ),
            SizedBox(width: 14.w),
            GestureDetector(
              onTap: () {
                // Get.to(MineChargeVipPage());
              },
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 5.h),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(90),
                  color: Color(globalStore.isVIP() ? 0xff3476FF : 0xffFFD5A8),
                ),
                child: Row(
                  children: [
                    Text(
                      '${globalStore.isVIP() ? '已开通会员' : '开通会员'}',
                      style: TextStyle(
                          color: Color(globalStore.isVIP() ? 0xfffffffff : 0xff663D00), fontSize: 12, fontWeight: FontWeight.w500),
                    ),
                    2.w.sizeBoxW,
                    SvgPicture.asset(
                      globalStore.isVIP() ? 'assets/images/hj_mine/vip_upgrade_arrow.svg' : 'assets/images/hj_mine/vip_arrow.svg',
                      width: 12,
                      height: 12,
                    )
                  ],
                ),
              ),
            ),
            SizedBox(width: 22),
          ],
        ),
      ],
    );
  }
}

/// vip引导New
class TaskCenterVIPGuideNewView extends StatefulWidget {
  const TaskCenterVIPGuideNewView({super.key});

  @override
  State<TaskCenterVIPGuideNewView> createState() => _TaskCenterVIPGuideNewViewState();
}

class _TaskCenterVIPGuideNewViewState extends State<TaskCenterVIPGuideNewView> {
  late final privilegeIcons = ['privilege_gold.webp'.mineImgPath, 'privilege_ai.webp'.mineImgPath, 'privilege_game.webp'.mineImgPath];
  late final privilegeTitles = ['至尊金币', 'AI科技', '成人游戏'];
  late final privilegeSubTs = ['价值100元', '价值500元', '价值1000元'];
  @override
  Widget build(BuildContext context) {
    return Consumer<GlobalStore>(builder: (_, store, __) {
      final isVip = store.isVIP();
      if (isVip) return _buildVIPNewGuide();
      return Column(
        children: [
          _buildVIPNewGuide(),
        ],
      );
    });
  }

  Widget _buildVIPGuide() {
    return Stack(
      alignment: Alignment.centerLeft,
      children: [
        Image.asset(
          globalStore.isVIP() ? 'welfare_vip_bg.webp'.mineImgPath : 'welfare_normal_bg.webp'.mineImgPath,
          width: double.infinity,
          fit: BoxFit.fitWidth,
        ),
        Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SizedBox(width: 22),
            Expanded(
              child: Consumer<MineMsgProvider>(
                builder: (context, provider, child) => Container(
                  margin: EdgeInsets.only(left: 2),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(
                            globalStore.isVIP()
                                ? '${globalStore.meInfo?.vipName == null || globalStore.meInfo?.vipName == '' ? '普通会员' : globalStore.meInfo?.vipName}'
                                : '新人限时特惠',
                            style: TextStyle(
                              color: globalStore.isVIP() ? Color(0xffFFE7CD) : Colors.white,
                              fontSize: 14,
                            ),
                          ),
                          if (!globalStore.isVIP())
                            Container(
                              padding: EdgeInsets.only(top: 2),
                              child: Text(
                                ' 领取双倍每日登录积分',
                                style: TextStyle(color: Color(0xffE3C891), fontSize: 10),
                              ),
                            ),
                        ],
                      ),
                      SizedBox(height: 5),
                      Text(
                        globalStore.isVIP()
                            ? '${globalStore.vipTime(hasVipName: false)}'
                            : ((provider.countdown?.leftTimeSinceEpoch ?? 0) > 0)
                                ? '新人限时特惠  ${provider.countdown?.hourDesc ?? '00'}:${provider.countdown?.minDesc ?? '00'}:${provider.countdown?.secondsDesc ?? '00'}'
                                : '活动已结束',
                        style: TextStyle(color: Color(0xffE7E7E7), fontWeight: FontWeight.w400, fontSize: 11),
                      )
                    ],
                  ),
                ),
              ),
            ),
            SizedBox(width: 14.w),
            GestureDetector(
              onTap: () {
                Get.to(MineChargeVipPage());
              },
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 5.h),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(90),
                  color: Color(globalStore.isVIP() ? 0xff3476FF : 0xffFFD5A8),
                ),
                child: Row(
                  children: [
                    Text(
                      '${globalStore.isVIP() ? '升级会员' : '开通会员'}',
                      style: TextStyle(
                          color: Color(globalStore.isVIP() ? 0xfffffffff : 0xff663D00), fontSize: 12, fontWeight: FontWeight.w500),
                    ),
                    2.w.sizeBoxW,
                    SvgPicture.asset(
                      globalStore.isVIP() ? 'assets/images/hj_mine/vip_upgrade_arrow.svg' : 'assets/images/hj_mine/vip_arrow.svg',
                      width: 12,
                      height: 12,
                    )
                  ],
                ),
              ),
            ),
            SizedBox(width: 22),
          ],
        ),
      ],
    );
  }

  Widget _buildVIPNewGuide() {
    return Container(
      height: 164,
      width: double.infinity,
      padding: EdgeInsets.fromLTRB(16, 16, 16, 0),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage("welfare_vip_background.webp".mineImgPath),
          fit: BoxFit.fill,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Consumer<MineMsgProvider>(
            builder: (context, provider, child) => Container(
              margin: EdgeInsets.only(left: 2),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  NetworkImageLoader(
                    imageUrl: globalStore.meInfo?.portrait ?? '',
                    width: 60,
                    height: 60,
                    borderRadius: 30,
                  ),
                  10.sizeBoxW,
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(
                            globalStore.meInfo?.name ?? "",
                            style: const TextStyle(color: const Color(0xFFFFFFFF), fontWeight: FontWeight.w500, fontSize: 18.0),
                          ),
                          globalStore.isVIP()
                              ? Image.asset(
                                  'assets/images/hj_mine/level_icon.webp',
                                  width: 36,
                                  height: 36,
                                )
                              : SizedBox(),
                        ],
                      ),
                      5.sizeBoxH,
                      globalStore.isVIP()
                          ? Text(
                              '到期时间： ${DateTimeUtil.utcTurnYear(globalStore.meInfo?.vipExpireDate, char: "-")}',
                              style: TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.w400,
                                foreground: Paint()
                                  ..shader = LinearGradient(
                                    colors: <Color>[Color(0xFFFFE8BE), Color(0xFFE6B764)],
                                  ).createShader(Rect.fromLTWH(0.0, 0.0, 120.0, 70.0)),
                              ),
                            )
                          : Consumer<PreSaleProvider>(
                              builder: (context, provider, child) => Text(
                                "剩余观看次数：${globalStore.meInfo?.watchCount ?? 0}",
                                style: TextStyle(fontSize: 10, color: Color(0xff989898)),
                              ),
                            )
                    ],
                  ),
                ],
              ),
            ),
          ),
          40.sizeBoxH,
          GestureDetector(
            onTap: () {
              // Get.to(MineChargeVipPage());
            },
            child: Container(
              height: 44,
              width: double.infinity,
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 5.h),
              margin: EdgeInsets.symmetric(horizontal: 40.w, vertical: 0),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(90),
                gradient: LinearGradient(
                  colors: [Color(0xFFFF9077), Color(0xFFFF6E4E)],
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                ),
              ),
              child: Text(
                '${globalStore.isVIP() ? '已开通会员' : '开通VIP不限次数观看'}',
                style: TextStyle(color: Color(globalStore.isVIP() ? 0xfffffffff : 0xfffffffff), fontSize: 16, fontWeight: FontWeight.w500),
              ),
            ),
          ),
          SizedBox(width: 22),
        ],
      ),
    );
  }
}

class MineTaskView extends StatefulWidget {
  final List<DailyTask> tasks;
  const MineTaskView(this.tasks, {super.key});

  @override
  State<MineTaskView> createState() => _MineTaskViewState();
}

class _MineTaskViewState extends State<MineTaskView> {
  int totalInvite = 0;
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      final record = await MineService.getProxyBindRecord(1, 1);
      totalInvite = record?.total ?? 0;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (widget.tasks.isEmpty) return SizedBox.shrink();
    return Container(
      child: Column(
        children: [
          12.sizeBoxH,
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 10),
            child: Row(
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '福利任务',
                      style: TextStyle(color: Colors.white, fontSize: 18.sp, fontWeight: FontWeight.w500),
                    ),
                    4.sizeBoxH,
                    Consumer<GlobalStore>(
                      builder: (_, provider, __) => Text(
                        '邀请人数$totalInvite人  我的积分${globalStore.wallet?.integral ?? 0}',
                        style: TextStyle(color: Color(0xff999999), fontSize: 14.sp, fontWeight: FontWeight.w400),
                      ),
                    ),
                  ],
                ),
                Spacer(),
                GestureDetector(
                  onTap: () => Get.to(ExchangeVipPage()),
                  child: Container(
                    height: 34,
                    width: 80,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(color: Color(0xffFFD460), borderRadius: BorderRadius.circular(4)),
                    child: Text(
                      '兑换VIP',
                      style: TextStyle(
                        color: Color(0xFF694923),
                        fontSize: 12,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ),
                )
              ],
            ),
          ),
          20.h.sizeBoxH,
          ListView.separated(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            separatorBuilder: (_, __) => 12.sizeBoxH,
            padding: EdgeInsets.only(left: 10, right: 10),
            // scrollDirection: Axis.horizontal,
            itemCount: widget.tasks.length,
            itemBuilder: (BuildContext context, int index) {
              return TaskItem(widget.tasks[index]);
            },
          ),
          // 20.sizeBoxH,
          // Padding(
          //   padding: EdgeInsets.symmetric(horizontal: 18.w),
          //   child: Divider(
          //     height: 1,
          //     color: Colors.white.withOpacity(.1),
          //   ),
          // )
        ],
      ),
    );
  }
}

class TaskItem extends StatefulWidget {
  final DailyTask task;
  const TaskItem(this.task, {super.key});

  @override
  State<TaskItem> createState() => _TaskItemState();
}

class _TaskItemState extends State<TaskItem> {
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10, vertical: 12),
      decoration: BoxDecoration(
        color: Color(0x0DFFFFFF),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          20.sizeBoxH,
          NetworkImageLoader(
            imageUrl: widget.task.img ?? '',
            width: 50,
            height: 50,
            borderRadius: 30,
          ),
          8.sizeBoxH,
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(
                      widget.task.title ?? "",
                      style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500, fontSize: 14),
                    ),
                  ],
                ),
                Text(
                  widget.task.desc?.toString() == null ? widget.task.subTitle.toString() : widget.task.desc.toString(),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: Color(0xffaaaaaa), fontSize: 12),
                )
              ],
            ),
          ),
          8.sizeBoxH,
          _buildTaskBtn(_getTaskStatus(widget.task.status), widget.task.status, () {
            switch (widget.task.status) {
              case 0: //未完成
                if (widget.task.title == "累计充值") {
                  Get.to(MineChargeCoinPage());
                  return;
                }
                pushToPageByLink(widget.task.link, id: widget.task.id);
                _doTask(widget.task);
                break;
              case 1: //待领取
                _receiveTask(widget.task.id, widget.task.doType);
            }
            if (widget.task.status != 2) {}
          }),
        ],
      ),
    );
  }

  void _doTask(DailyTask task) async {
    bool needDotask = (task.doType == 1 && task.type == 0) || (task.doType == 2 && task.type == 2);
    if (needDotask) {
      final res = await CommonService.doTask(task.id ?? "", task.doType);
      if (res) {
        widget.task.setStatus(1);

        setState(() {});
      }
    }
  }

  void _receiveTask(String? taskId, int? type) async {
    final res = await MineService.receiveIntegral(taskId, type);
    if (res) {
      widget.task.setStatus(2);
      globalStore.refreshWallet();
      setState(() {});
    }
  }

  String _getTaskStatus(int? status) {
    var tStatus = "去完成";
    switch (status) {
      case 0:
        tStatus = "去完成";
        break;
      case 1:
        tStatus = "待领取";
        break;
      case 2:
        tStatus = "已领取";
        break;
    }
    return tStatus;
  }

  Widget _buildTaskBtn(String btnTxt, int? status, Function? callClick) {
    return InkWell(
      onTap: () => callClick?.call(),
      child: Container(
        width: 70,
        height: 32,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(4)),
            color: status == 1
                ? Color(0xffFFD5A8)
                : status == 2
                    ? Color(0xffB3B3B3)
                    : Color(0xffE1351F)),
        child: Center(
          child: Text(
            btnTxt,
            style: TextStyle(
              color: status == 1 ? Color(0xff692A1F) : Colors.white,
              fontWeight: FontWeight.w500,
              fontSize: 14.0,
            ),
          ),
        ),
      ),
    );
  }
}
